/*
 * $Id: Text.java 53 2009-04-12 10:36:20Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.gui.deltagui.widget;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.util.StringTokenizer;

/**
 * Text.
 * 
 * @author Andreas Meyer
 * @version $Revision: 53 $
 */
public class Text extends Control {

	/** The text. */
	private String text;

	
	/**
	 * Construct the text.
	 * 
	 */
	public Text() {
		
	}

	/**
	 * Construct the button.
	 * 
	 * @param text
	 */
	public Text(final String text) {

		setText(text);
		
		if(text == null) {
			setName("<empty>");
		} else {
			
			if(text.length() > 10) {
				setName(text.substring(0, 10));
			} else {
				setName(text);
			}
		}
	}

	/**
	 * @return the text
	 */
	public String getText() {
		return text;
	}

	/**
	 * @param text the text to set
	 */
	public void setText(final String text) {
		this.text = text;
		
		setUnrendered();
	}

	/**
	 * @see deltadesk.gui.deltagui.widget.Control#isFocusable()
	 */
	@Override
	public boolean isFocusable() {
		return false;
	}

	/**
	 * @see deltadesk.gui.deltagui.widget.Control#renderControl(java.awt.Graphics2D)
	 */
	@Override
	public void renderControl(final Graphics2D g2) {

		g2.setColor(Color.BLACK);
		
		if(text == null) {
			
			return;
		}
		
		final Font f = getFont();
		final FontMetrics fm = g2.getFontMetrics(f);
		int h = fm.getHeight();
		
		int x = 10;
		int y = h;
		
		//TODO: better algorithm
		final StringTokenizer st = new StringTokenizer(text, " \n", true);
		while(st.hasMoreTokens()) {
			
			final String tok = st.nextToken();
			if(tok.equals("\n")) {

				x = 10;
				y += h;
				continue;
			} else if(tok.equals(" ")) {
				x+=7;
				continue;
			}
			
			final int w = fm.stringWidth(tok);
			if(x + w + 10 > getWidth()) {
				x = 10;
				y += h;
			}
			
			g2.drawString(tok, x, y);

			x += fm.stringWidth(tok);
		
		} // end while
	}

}
